<?php

namespace app\admin\model\yalimedia\course;

use think\Model;

class Content extends Model
{
    // 表名
    protected $name = 'yalimedia_course_content';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $model = new self();
            $count = $model->where(['course_id'=>$row['course_id'],'unit_id'=>$row['unit_id']])->count();

            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => ($count)]);
        });
    }

    public static function sort($course_id,$unit_id,$content_id,$old_weigh,$new_weigh){

        $unitModel = new Content();
        $total = $unitModel->where(['course_id'=>$course_id,'unit_id'=>$unit_id])->count();
        if($new_weigh<=0){
            $new_weigh = 1;
        }else if($new_weigh >= $total){
            $new_weigh = $total;
        }
        if($new_weigh >= $old_weigh){
            $unitModel = new Content();
            $unitModel->where(['course_id'=>$course_id,'unit_id'=>$unit_id,'weigh'=>[['elt',$new_weigh],['gt',$old_weigh]]])->setDec('weigh');
        }else{

            $unitModel = new Content();
            $unitModel->where(['course_id'=>$course_id,'unit_id'=>$unit_id,'weigh'=>[['egt',$new_weigh],['lt',$old_weigh]]])->setInc('weigh');
        }

        $unitModel = new Content();
        $unitModel->where(['course_id'=>$course_id,'unit_id'=>$unit_id,'id'=>$content_id])->update(['weigh'=>$new_weigh]);


    }
}
